<template>
    <div class="create-group-modal">
        <div class="modal-header">
            <van-button size="small" @click="handleClose">Cancel</van-button>
            <h3>Create Group</h3>
            <van-button size="small" type="primary" :loading="submitting" :disabled="!canSubmit" @click="handleSubmit">
                Create
            </van-button>
        </div>

        <div class="modal-content">
            <!-- 群组头像 -->
            <div class="avatar-section">
                <div class="avatar-upload" @click="selectAvatar">
                    <van-image v-if="groupAvatar" :src="groupAvatar" width="80" height="80" round fit="cover" />
                    <div v-else class="avatar-placeholder">
                        <van-icon name="plus" />
                        <span>Add Photo</span>
                    </div>
                </div>
                <input ref="avatarInput" type="file" accept="image/*" style="display: none"
                    @change="handleAvatarSelect" />
            </div>

            <!-- 基本信息 -->
            <div class="basic-info">
                <van-field v-model="groupName" label="Group Name" placeholder="Enter group name" :maxlength="50"
                    show-word-limit required />

                <van-field v-model="groupDescription" label="Description" type="textarea"
                    placeholder="Describe your group's purpose and goals..." :maxlength="200" show-word-limit
                    autosize />
            </div>

            <!-- 群组设置 -->
            <div class="group-settings">
                <div class="setting-item">
                    <div class="setting-info">
                        <div class="setting-title">Private Group</div>
                        <div class="setting-desc">Only invited members can join</div>
                    </div>
                    <van-switch v-model="isPrivate" />
                </div>

                <div class="setting-item">
                    <div class="setting-info">
                        <div class="setting-title">Require Approval</div>
                        <div class="setting-desc">Admin approval needed for new members</div>
                    </div>
                    <van-switch v-model="requireApproval" />
                </div>

                <div class="setting-item">
                    <div class="setting-info">
                        <div class="setting-title">Allow Invites</div>
                        <div class="setting-desc">Members can invite others</div>
                    </div>
                    <van-switch v-model="allowInvites" />
                </div>
            </div>

            <!-- 分类选择 -->
            <div class="category-section">
                <div class="section-title">Category</div>
                <div class="category-grid">
                    <div v-for="category in categories" :key="category.id" class="category-item"
                        :class="{ active: selectedCategory === category.id }" @click="selectedCategory = category.id">
                        <van-icon :name="category.icon" />
                        <span>{{ category.name }}</span>
                    </div>
                </div>
            </div>

            <!-- 标签选择 -->
            <div class="tags-section">
                <div class="section-title">Tags</div>
                <div class="tags-input">
                    <van-field v-model="tagInput" placeholder="Add tags (press Enter to add)" @keyup.enter="addTag" />
                </div>
                <div class="tags-list" v-if="tags.length > 0">
                    <van-tag v-for="tag in tags" :key="tag" closeable @close="removeTag(tag)" type="primary">
                        {{ tag }}
                    </van-tag>
                </div>
                <div class="suggested-tags">
                    <span class="suggested-title">Suggested:</span>
                    <van-tag v-for="suggestedTag in suggestedTags" :key="suggestedTag" plain
                        @click="addSuggestedTag(suggestedTag)">
                        {{ suggestedTag }}
                    </van-tag>
                </div>
            </div>

            <!-- 初始成员邀请 -->
            <div class="invite-section">
                <div class="section-title">Invite Members (Optional)</div>
                <van-field v-model="inviteEmails" type="textarea"
                    placeholder="Enter email addresses, separated by commas" autosize />
                <div class="invite-note">
                    <van-icon name="info-o" />
                    <span>Invitations will be sent after group creation</span>
                </div>
            </div>

            <!-- 群组规则 -->
            <div class="rules-section">
                <div class="section-title">Group Rules (Optional)</div>
                <van-field v-model="groupRules" type="textarea" placeholder="Set community guidelines and rules..."
                    :maxlength="500" show-word-limit autosize />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { showToast } from 'vant'

interface Emits {
    (e: 'submit', data: any): void
    (e: 'close'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const submitting = ref(false)
const groupName = ref('')
const groupDescription = ref('')
const groupAvatar = ref('')
const isPrivate = ref(false)
const requireApproval = ref(false)
const allowInvites = ref(true)
const selectedCategory = ref(1)
const tagInput = ref('')
const tags = ref<string[]>([])
const inviteEmails = ref('')
const groupRules = ref('')

const avatarInput = ref<HTMLInputElement>()

// 分类数据
const categories = ref([
    { id: 1, name: 'Communication', icon: 'chat-o' },
    { id: 2, name: 'Leadership', icon: 'manager-o' },
    { id: 3, name: 'Teamwork', icon: 'friends-o' },
    { id: 4, name: 'Presentation', icon: 'play-circle-o' },
    { id: 5, name: 'Negotiation', icon: 'balance-o' },
    { id: 6, name: 'General', icon: 'apps-o' }
])

// 建议标签
const suggestedTags = ref([
    'beginner-friendly',
    'advanced',
    'practice',
    'feedback',
    'networking',
    'career-growth'
])

// 计算属性
const canSubmit = computed(() => {
    return groupName.value.trim().length > 0 &&
        groupDescription.value.trim().length > 0
})

// 方法
const selectAvatar = () => {
    avatarInput.value?.click()
}

const handleAvatarSelect = (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (file) {
        if (file.size > 5 * 1024 * 1024) {
            showToast('Image size should be less than 5MB')
            return
        }

        const reader = new FileReader()
        reader.onload = (e) => {
            groupAvatar.value = e.target?.result as string
        }
        reader.readAsDataURL(file)
    }

    target.value = ''
}

const addTag = () => {
    const tag = tagInput.value.trim().toLowerCase()
    if (tag && !tags.value.includes(tag)) {
        if (tags.value.length >= 10) {
            showToast('Maximum 10 tags allowed')
            return
        }
        tags.value.push(tag)
        tagInput.value = ''
    }
}

const removeTag = (tag: string) => {
    const index = tags.value.indexOf(tag)
    if (index > -1) {
        tags.value.splice(index, 1)
    }
}

const addSuggestedTag = (tag: string) => {
    if (!tags.value.includes(tag)) {
        if (tags.value.length >= 10) {
            showToast('Maximum 10 tags allowed')
            return
        }
        tags.value.push(tag)
    }
}

const handleSubmit = async () => {
    if (!canSubmit.value) return

    submitting.value = true

    try {
        const groupData = {
            name: groupName.value.trim(),
            description: groupDescription.value.trim(),
            avatar: groupAvatar.value,
            is_private: isPrivate.value,
            require_approval: requireApproval.value,
            allow_invites: allowInvites.value,
            category_id: selectedCategory.value,
            tags: tags.value,
            invite_emails: inviteEmails.value.split(',').map(email => email.trim()).filter(Boolean),
            rules: groupRules.value.trim()
        }

        emit('submit', groupData)
    } catch (error) {
        console.error('Failed to create group:', error)
        showToast('Failed to create group')
    } finally {
        submitting.value = false
    }
}

const handleClose = () => {
    emit('close')
}
</script>

<style lang="scss" scoped>
.create-group-modal {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: white;

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid #ebedf0;

        h3 {
            font-size: 18px;
            font-weight: 600;
            color: #323233;
            margin: 0;
        }
    }

    .modal-content {
        flex: 1;
        padding: 20px;
        overflow-y: auto;

        .avatar-section {
            text-align: center;
            margin-bottom: 24px;

            .avatar-upload {
                display: inline-block;
                cursor: pointer;

                .avatar-placeholder {
                    width: 80px;
                    height: 80px;
                    border: 2px dashed #dcdee0;
                    border-radius: 50%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    color: #969799;
                    transition: all 0.3s ease;

                    &:hover {
                        border-color: #1989fa;
                        color: #1989fa;
                    }

                    .van-icon {
                        font-size: 20px;
                        margin-bottom: 4px;
                    }

                    span {
                        font-size: 12px;
                    }
                }
            }
        }

        .basic-info {
            margin-bottom: 24px;

            :deep(.van-field) {
                margin-bottom: 16px;
                background: #f7f8fa;
                border-radius: 8px;
            }
        }

        .group-settings {
            margin-bottom: 24px;

            .setting-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .setting-info {
                    flex: 1;

                    .setting-title {
                        font-size: 15px;
                        font-weight: 500;
                        color: #323233;
                        margin-bottom: 4px;
                    }

                    .setting-desc {
                        font-size: 13px;
                        color: #969799;
                        line-height: 1.4;
                    }
                }
            }
        }

        .category-section,
        .tags-section,
        .invite-section,
        .rules-section {
            margin-bottom: 24px;

            .section-title {
                font-size: 16px;
                font-weight: 600;
                color: #323233;
                margin-bottom: 12px;
            }
        }

        .category-section {
            .category-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 8px;

                .category-item {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    padding: 12px 8px;
                    background: #f7f8fa;
                    border-radius: 8px;
                    cursor: pointer;
                    transition: all 0.3s ease;

                    &:hover {
                        background: #e8f3ff;
                    }

                    &.active {
                        background: #1989fa;
                        color: white;
                    }

                    .van-icon {
                        font-size: 20px;
                        margin-bottom: 4px;
                    }

                    span {
                        font-size: 12px;
                        text-align: center;
                    }
                }
            }
        }

        .tags-section {
            .tags-input {
                margin-bottom: 12px;

                :deep(.van-field) {
                    background: #f7f8fa;
                    border-radius: 8px;
                }
            }

            .tags-list {
                display: flex;
                gap: 6px;
                flex-wrap: wrap;
                margin-bottom: 12px;
            }

            .suggested-tags {
                display: flex;
                align-items: center;
                gap: 6px;
                flex-wrap: wrap;

                .suggested-title {
                    font-size: 13px;
                    color: #646566;
                    margin-right: 6px;
                }

                .van-tag {
                    cursor: pointer;
                }
            }
        }

        .invite-section {
            :deep(.van-field) {
                background: #f7f8fa;
                border-radius: 8px;
                margin-bottom: 8px;
            }

            .invite-note {
                display: flex;
                align-items: center;
                gap: 6px;
                font-size: 12px;
                color: #969799;

                .van-icon {
                    color: #1989fa;
                }
            }
        }

        .rules-section {
            :deep(.van-field) {
                background: #f7f8fa;
                border-radius: 8px;
            }
        }
    }
}
</style>